import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import cart from "../../../../store/cart";
import { getShopStatus } from "@src/api/catering";

Component({
  options: {
    addGlobalClass: true,
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: cart,
      actions: ["addCart", "shopId"],
      fieds: ["shop_isOpen"],
    },
  ],
  data: {
    visible: false,
    goods: null,
    spec: "",
    specPrice: 0,
    resolve: null,
    reject: null,
    selectAttrList: [],
    tips: "",
    isFold: false,
    goodImg: [],
    giftStr: "",
    proNum: 1,
    shopId: "",
    isOpen: false,
    isOpenTime: true,
    isFixedTitle: false,
  },
  observers: {
    "spec,selectAttrList": function (spec, selectAttrList) {
      let tips = [];
      if (spec) {
        tips.push(spec);
      }
      tips.push(...selectAttrList);
      this.setData({
        tips: tips.join(","),
      });
    },
    shopId: function (shopId) {
      if (shopId) {
        this.setShopStatus();
      }
    },
  },
  methods: {
    handleClose() {
      this.setData({
        visible: false,
        proNum: 1,
      });
    },
    handleStop() {
      return true;
    },
    open(goods, shopId) {
      this.setData({
        shopId,
      });
      this.reset(goods);
      this.setData({
        visible: true,
      });
      this.setShopStatus();
    },
    reset(goods) {
      // this.setData({
      //   shopId: getApp().globalData.dinnerShopid
      // })
      let { ruleList } = goods;
      let giftStr = [];
      let spec = "",
        specPrice,
        selectAttrList = [];
      if (goods.specList && goods.specList.length > 0) {
        spec = goods.specList[0].name;
        specPrice = goods.specList[0].price;
      }
      // 商品轮播图
      if (goods.itemImages) {
        let imgList = goods.itemImages.split(",");
        let fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl;
        imgList.forEach((el, index) => {
          imgList[index] = fileBaseUrl + el;
        });
        this.setData({
          goodImg: imgList,
        });
      } else {
        this.setData({
          goodImg: [goods.imageUrl],
        });
      }
      // 展示赠品信息
      if (ruleList && ruleList.length > 0) {
        ruleList.forEach((e) => {
          if (e.enItemGiftRules && e.enItemGiftRules.length > 0) {
            e.enItemGiftRules.forEach((ele) => {
              giftStr.push(
                `购买${ele.itemNum}份商品赠送${e.sellgiftName}x${ele.giftNum}`
              );
            });
          }
        });
      }
      // 默认设置第一个属性
      if (goods.attrList && goods.attrList.length > 0) {
        for (let item of goods.attrList) {
          selectAttrList.push(item.values[0]);
        }
      }
      this.setData({
        goods,
        spec,
        specPrice,
        selectAttrList,
        giftStr,
      });
    },
    handleSelectSpec(e) {
      let item = e.currentTarget.dataset.item;
      if (item.name === this.data.spec) {
        return;
      }
      this.setData({
        spec: item.name,
        specPrice: item.price,
        proNum: 1,
      });
    },
    handleSelectAttr(e) {
      let { index, value } = e.currentTarget.dataset;
      let selectAttrList = this.data.selectAttrList;
      selectAttrList[index] = value;
      this.setData({
        selectAttrList,
        proNum: 1,
      });
    },
    handleConfirm() {
      let item = {};
      let {
        goods: { name, price, specList, id, imageUrl, ruleList },
        specPrice,
        selectAttrList,
        spec,
        proNum,
        tips,
      } = this.data;
      item = {
        name,
        id,
        count: proNum,
        imageUrl,
        spec,
        ruleList,
        price: spec ? specPrice : price,
        attrList: selectAttrList,
        remark: tips,
      };

      this.addCart(item);
      this.setData({
        proNum: 1,
      });
      this.setData({
        visible: false,
      });
    },

    handleMinus(e) {
      let op = e.currentTarget.dataset.op;
      if (op === "multi-spec") {
        this.handleOpSpec("reduce");
      }
      for (let i = 0; i < this.data.proNum - Number(e.detail); i++) {
        if (op === "not-multi-spec") {
          this.handleOp("reduce");
        }
      }
    },
    handlePlus(e) {
      let op = e.currentTarget.dataset.op;
      if (op === "multi-spec") {
        this.handleOpSpec("add");
      }
      for (let i = 0; i < Number(e.detail) - this.data.proNum; i++) {
        if (op === "not-multi-spec") {
          this.handleOp("add");
        }
      }
    },

    handleOp(op) {
      // let {
      //   op
      // } = e.currentTarget.dataset
      let { proNum } = this.data;
      if (op == "reduce") {
        if (proNum <= 1) {
          wx.showToast({
            title: "数量不能小于1",
            icon: "error",
            duration: 2000,
          });
          return;
        }
        this.setData({
          proNum: proNum - 1,
        });
      } else {
        if (proNum > 99) {
          wx.showToast({
            title: "数量不能大于99",
            icon: "error",
            duration: 2000,
          });
          return;
        }
        this.setData({
          proNum: proNum + 1,
        });
      }
    },
    async handleToPay() {
      this.setShopStatus().then((res) => {
        if (res) {
          let item = {};
          let {
            goods: { name, price, specList, id, imageUrl, ruleList },
            specPrice,
            selectAttrList,
            spec,
            proNum,
            tips,
          } = this.data;
          item = {
            name,
            id,
            count: proNum,
            imageUrl,
            spec,
            ruleList,
            price: spec ? specPrice : price,
            attrList: selectAttrList,
            remark: tips,
          };
          let allPrice = (item.price * proNum).toFixed(2);
          this.triggerEvent("pay", {
            carList: [item],
            totalFree: allPrice,
          });
          this.setData({
            proNum: 1,
          });
          this.setData({
            visible: false,
          });
        }
      });
    },
    changeDese() {
      let {
        data: { isFold },
      } = this;
      this.setData({
        isFold: !isFold,
      });
    },
    sharePro() {
      let { goods, shopId } = this.data;
      this.selectComponent("#sharePro").handleToSavePoster(goods, shopId);
      this.handleClose();
    },
    async setShopStatus() {
      console.log(this.data);
      let isOpenTime = true;
      let res = await getShopStatus({
        shopId: this.data.shopId,
      });
      let { isOpen, status, disabled } = res.data;
      isOpenTime =
        isOpen === true && (status === 1 || status === 2) && disabled === false;
      this.setData({
        isOpenTime,
      });
      return isOpenTime;
    },

    // },
    scroll(e) {
      let { scrollTop, titleHight = 211 } = e.detail;
      let isFixedTitle = scrollTop > titleHight ? true : false;
      this.setData({
        isFixedTitle,
      });
    },
  },
});
